<template>
  <div class="menu">
    <el-row>
      <el-col :xs="24" :lg="10">
        <el-card class="box-card left">
          <el-tree
            :data="tree.data"
            ref="tree"
            node-key="id"
            @node-click="treeClick"
            :default-expanded-keys="['app_' + USER.app.id]"
            accordion
            :render-content="treeContent">
          </el-tree>
          <div style="margin-top: 5px">
            <span style="width: 100px;display: inline-block">调整菜单</span>
            <el-switch
              v-model="menuUpdate"
              on-text="开"
              off-text="关"
              on-color="#13ce66"
              off-color="#ff4949">
            </el-switch>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="14">
        <el-card class="box-card right">
          <div slot="header" class="clearfix">
            <span style="line-height: 36px;"> {{tree.select.menuName || '菜单'}} 详情</span>
            <el-button style="float: right;" type="success" v-if="tree.select.id !== 0" @click="dialogOpen('PUT', tree.select)">修改</el-button>
          </div>
          <el-form :model="tree.select" labelWidth="80px" label-position="left" v-if="tree.select.id !== 0">
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="mc" label="菜单名称"><span>{{tree.select.mc}}</span></el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}">
                <el-form-item prop="tb" label="菜单图标"><span><i :class="['menuIcon','fa', 'fa-' + tree.select.tb]"></i> {{tree.select.tb}}</span></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="lj" label="菜单路径"><span>{{tree.select.lj}}</span></el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}">
                <el-form-item prop="code" label="菜单编码"><span>{{tree.select.code}}</span></el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="wz" label="菜单位置"><span>{{tree.select.wz}}</span></el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}">
                <el-form-item prop="ms" label="菜单描述"><span>{{tree.select.ms}}</span></el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <p v-else>点击菜单树，查看详情</p>
        </el-card>
      </el-col>
    </el-row>

    <s-dialog :dialog="dialog" :close="dialogInit">
      <el-tabs v-model="dialog.activeName" @tab-click="tabsClick">
        <el-tab-pane name="menu" :disabled="dialog.both">
          <span slot="label"><i class="el-icon-date"></i> {{dialog.title}}菜单</span>
          <s-form :form="formDialog" ref="formDialog">
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="mc" label="菜单名称">
                  <el-input
                    type="text"
                    v-model="formDialog.mc"
                    placeholder="菜单名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}">
                <el-form-item prop="code" label="菜单编码">
                  <el-input
                    type="text"
                    v-model="formDialog.code"
                    placeholder="菜单项编码"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="lj" label="菜单路径">
                  <el-input
                    type="text"
                    v-model="formDialog.lj"
                    placeholder="菜单路径地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}">
                <el-form-item prop="tb" label="菜单图标">
                  <el-input
                    type="text"
                    v-model="formDialog.tb"
                    placeholder="菜单图标地址"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </s-form>
        </el-tab-pane>
        <el-tab-pane name="func" :disabled="dialog.both">
          <span slot="label"><i class="el-icon-date"></i> {{dialog.title}}功能</span>
          <s-form :form="formDialogFunc" ref="formDialogFunc">
            <el-row>
              <el-col :xs="24" :lg="{span: 11, offset: 0}">
                <el-form-item prop="mc" label="功能名称">
                  <el-input
                    type="text"
                    v-model="formDialogFunc.mc"
                    placeholder="功能名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}">
                <el-form-item prop="code" label="功能项编码">
                  <el-input
                    type="text"
                    v-model="formDialogFunc.code"
                    placeholder="功能项编码"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </s-form>
        </el-tab-pane>
      </el-tabs>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue} from '~/plugins/Tools';
  /**
   * 模板思想
   */
  function __form () {
    return {
      id: { value: '', rule: [], cRemarks: '' },
      mc: { value: '', rule: [ 'vNull' ], cRemarks: '' },
      tb: { value: '', rule: [], cRemarks: '' },
      lj: { value: '', rule: [], cRemarks: '' },
      fjd: { value: '', rule: [], cRemarks: '' },
      wz: { value: '', rule: [], cRemarks: '' },
      ms: { value: '', rule: [], cRemarks: '' },
      kh: { value: '', rule: [], cRemarks: '' },
      code: { value: '', rule: [ 'vNull' ], cRemarks: '' },
      sq: { value: '1', rule: [], cRemarks: '0未授权 1已授权' } };
  }
  function __formFunc () {
    return { sscdid: { value: '', rule: [], cRemarks: '' },
      mc: { value: '', rule: [ 'vNull' ], cRemarks: '' },
      px: { value: '', rule: [], cRemarks: '' },
      code: { value: '', rule: [ 'vNull' ], cRemarks: '' },
      id: { value: '', rule: [], cRemarks: '' } };
  }
  function __form_select () {
    return { mc: '',
      tb: '',
      lj: '',
      fjd: '',
      wz: '',
      ms: '',
      kh: '',
      code: '',
      sq: '1',
      show_sq: '',
      id: '' };
  }
  export default AutoVue({
    name: 'menu-safety',
    transition: 'slide-fade',
    data: {
      tree: {
        data: [],
        select: __form_select(),
      },
      dialog: {
        title: '新增',
        saveParameter: {},
        formRef: 'formDialog',
        activeName: 'menu',
        menu: true,
        both: false,
      },
      formDialog: __form(),
      formDialogFunc: __formFunc(),
      menuUpdate: false,
    },
    store: {
      s: ['CUSTOM_customers', 'USER', 'MENU'],
    },
    methods: {
      treeContent (h, { node, data, store }) {
        return (
          <span class="treeContent">
            <span>
              <span class={{'isFunc': !data.menuCode && !data.menuLevel}}>{data.label}<span class={{'isFuncCode': true, 'display': data.menuCode || data.menuLevel}}>{data.code}</span></span>
            </span>
            <span class="treeContentButton">
              <el-button size="mini" type="primary" class={{ 'display': !this.menuUpdate || node.level === 1 || !data.menuCode }} on-click={ event => this.treeMenuUpdate(event, store, data, -1) }><i class="fa fa-arrow-up" aria-hidden="true"></i></el-button>
              <el-button size="mini" type="danger" class={{ 'display': !this.menuUpdate || node.level === 1 || !data.menuCode }} on-click={ event => this.treeMenuUpdate(event, store, data, 1) }><i class="fa fa-arrow-down" aria-hidden="true"></i></el-button>
              <el-button size="mini" type="primary" icon="plus" class={{ 'display': this.menuUpdate || !(data.menuCode || data.menuLevel) }} on-click={ event => this.treeAppend(event, store, data) }></el-button>
              <el-button size="mini" type="success" icon="edit" class={{ 'display': this.menuUpdate || data.menuCode || data.menuLevel }} on-click={ event => this.treeEdit(event, store, data) }></el-button>
            </span>
          </span>);
      },
      treeClick (data, node, tree) {
        if (data.menuLevel) return;
        if (!data.menuCode) return;
        this.tree.select = data;
      },
      treeAppend (event, store, data) {
        this.dialogOpen('ADD', {store, data});
        event.stopPropagation();
      },
      treeEdit (event, store, data) {
        this.dialogOpen('PUT', {store, data});
        event.stopPropagation();
      },
      treeMenuUpdate (event, store, data, type) {
        this.$confirm(`您将${type === -1 ? '升' : '降'}本节点。`, '确认？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/sysMenu/updateWz', {
                id: data.id,
                showOrder: type,
              });
              let parent = store.nodesMap[data.id + ''].parent;
              let parentNodes = [];

              for (let item of parent.childNodes) {
                parentNodes.push(Object.assign({}, item));
              }
              let stepNodes = [];
              let index = parentNodes.findIndex(function (value, index, arr) {
                return value.data.id === data.id;
              });
              for (let item of parentNodes) {
                stepNodes.push(item.data);
                parent.store.remove(item.data);
              }
              stepNodes[index] = stepNodes.splice(index + type, 1, stepNodes[index])[0];
              for (let item of stepNodes) {
                store.append(item, parent.data);
              }
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {});
        event.stopPropagation();
      },
      dialogInit (formRef) {
        this.dialog.title = '新增';
        this.dialog.activeName = 'menu';
        this.dialog.saveParameter = {};
        this.dialog.menu = true;
        this.dialog.both = false;
        let obj = {};
        switch (formRef) {
        case 'formDialog':
          obj = __form();
          break;
        }
        this[formRef] = {
          ...this[formRef],
          ...this.ObjectClone(obj),
        };
        this.resetFields(formRef);
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        }
        /*
        if (!this.DICTIONARY_menu) {
          await this.USE('DICTIONARY_menu');
        }
        */
        let data = more.data || more;
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.dialog.both = true;
          this.dialog.saveParameter = more;
          if (data.id.indexOf('_') !== -1) {
            this.formDialog.fjd = '0';
            this.formDialogFunc.sscdid = '0';
          } else {
            this.formDialog.fjd = data.id;
            this.formDialogFunc.sscdid = data.id;
          }
          if (data.children && data.children.length > 0) {
            this.formDialog.wz = data.children.length + 1;
            this.formDialogFunc.px = data.children.length + 1;
            this.dialog.activeName = data.children[0].show_sq ? 'menu' : 'func';
          } else {
            this.formDialog.wz = 1;
            this.formDialogFunc.px = 1;
            this.dialog.both = false;
          }
          break;
        case 'PUT':
          this.dialog.menu = !!data.show_sq;
          this.dialog.both = true;
          this.dialog.title = '修改';
          if (this.dialog.menu) {
            for (let index in __form()) {
              this.formDialog[index] = data[index];
            }
          } else {
            this.dialog.activeName = 'func';
            for (let index in __formFunc()) {
              this.formDialogFunc[index] = data[index];
            }
            this.formDialogFunc.mc = data.label;
          }
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        let more = this.dialog.saveParameter;
        if (this.dialog.title === '新增') {
          if (this.dialog.activeName === 'menu') {
            this.VALIDATE('formDialog', async (option) => {
              try {
                let {data} = await this.post('/sysMenu/add', option);
                more.store.append(data, more.data);
                this.dialogInit('formDialog');
                this.dialog.visible = false;
              } catch (err) {
                console.log(err);
              }
            });
          } else {
            this.VALIDATE('formDialogFunc', async (option) => {
              try {
                let {data} = await this.post('/sysFunction/add', option);
                more.store.append(data, more.data);
                this.dialogInit('formDialogFunc');
                this.dialog.visible = false;
              } catch (err) {
                console.log(err);
              }
            });
          }
        } else {
          if (this.dialog.activeName === 'menu') {
            this.VALIDATE('formDialog', async (option) => {
              try {
                let {data} = await this.post('/sysMenu/edit', option);
                this.tree.select = data;
                let nodesMap = this.$refs.tree.store.nodesMap[option.id + ''];
                data.children = nodesMap.data.children;
                nodesMap.data = data;
                this.dialogInit('formDialog');
                this.dialog.visible = false;
              } catch (err) {
                console.log(err);
              }
            });
          } else {
            this.VALIDATE('formDialogFunc', async (option) => {
              try {
                let {data} = await this.post('/sysFunction/edit', option);
                this.tree.select = data;
                this.$refs.tree.store.nodesMap[option.id + ''].data = this.tree.select;
                this.dialogInit('formDialogFunc');
                this.dialog.visible = false;
              } catch (err) {
                console.log(err);
              }
            });
          }
        }
      },
      tabsClick (tab, event) {
        console.log(tab, event);
      },
    },
    async mounted () {
      if (this.tree.data.length !== 0) return;
      let app = Object.assign(this.USER.app);
      if (this.MENU.menu.length === 0) {
        this.SET('MENU', await this.post('/sysMenu/getMenus'));
      }
      this.tree.data = [{
        id: 'app_' + app.id,
        menuLevel: '-1',
        label: app.aName,
        children: Object.assign(this.MENU.menu),
      }];
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }
  .el-tag{
    font-size: 14px;
  }
  .createTime{
    margin-bottom: -20px;
    z-index: -1;
    position: relative;
  }
  @media screen and (max-width: 800px) {
    .box-card {
      margin: 0;
    }
    .left{
      border: none;
      border-radius: 0;
      overflow: auto;
      box-shadow: none;
    }
    .createTime{
      margin-bottom: -45px;
    }
  }
</style>

<style lang="scss">
  .isFunc{
    color: #41c3ff;
  }
  .isFuncCode{
    margin-left: 10px;
    color: #d35e56;
  }
  .treeContent{
    position: relative;
    display: inline-block;
    width: calc(100% - 25px);
    .treeContentButton{
      position: absolute;
      right: 20px;
    }
  }
</style>
